package io.gitee.twoke.generator.engine.impl.interceptor;

import io.gitee.twoke.generator.engine.impl.cfg.GenerateEngineConfigurationImpl;
import io.gitee.twoke.generator.engine.impl.context.Context;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CommandContextInterceptor extends AbstractCommandInterceptor {

  protected CommandContextFactory commandContextFactory;
  protected GenerateEngineConfigurationImpl generateEngineConfiguration;

  public CommandContextInterceptor() {
  }

  public CommandContextInterceptor(CommandContextFactory commandContextFactory, GenerateEngineConfigurationImpl generateEngineConfiguration) {
    this.commandContextFactory = commandContextFactory;
    this.generateEngineConfiguration = generateEngineConfiguration;
  }

  public <T> T execute(CommandConfig config, Command<T> command) {
    CommandContext context = Context.getCommandContext();

    boolean contextReused = false;
    // We need to check the exception, because the transaction can be in a
    // rollback state, and some other command is being fired to compensate (eg. decrementing job retries)
    if (!config.isContextReusePossible() || context == null || context.getException() != null) {
      context = commandContextFactory.createCommandContext(command);
    } else {
      log.debug("Valid context found. Reusing it for the current command '{}'", command.getClass().getCanonicalName());
      contextReused = true;
      context.setReused(true);
    }

    try {
      
      // Push on stack
      Context.setCommandContext(context);
      Context.setGenerateEngineConfiguration(generateEngineConfiguration);
      return next.execute(config, command);

    } catch (Throwable e) {

      context.exception(e);
      
    } finally {
      try {
        if (!contextReused) {
          context.close();
        }
      } finally {
        
        // Pop from stack
        Context.removeCommandContext();
        Context.removeGenerateEngineConfiguration();
      }
    }

    return null;
  }

  public CommandContextFactory getCommandContextFactory() {
    return commandContextFactory;
  }

  public void setCommandContextFactory(CommandContextFactory commandContextFactory) {
    this.commandContextFactory = commandContextFactory;
  }

  public GenerateEngineConfigurationImpl getGenerateEngineConfiguration() {
    return generateEngineConfiguration;
  }

  public void setGenerateEngineConfiguration(GenerateEngineConfigurationImpl generateEngineConfiguration) {
    this.generateEngineConfiguration = generateEngineConfiguration;
  }
}